/**
 * 通用JS方法封装处理
 * Copyright (c) 2019 ruoyi
 */


// 字符串格式化(%s )
export function sprintf(format: string, ...args: any[]): string {
    let flag = true;
    format = format.replace(/%s/g, () => {
        const arg = args.shift();
        if (typeof arg === 'undefined') {
            flag = false;
            return '';
        }
        return arg;
    });
    return flag ? format : '';
}

// 转换字符串，undefined,null等转化为""
export function parseStrEmpty(str: any): string {
    if (!str || str === 'undefined' || str === 'null') {
        return '';
    }
    return str;
}

// 数据合并
export function mergeRecursive(source: any, target: any): any {
    for (const p in target) {
        try {
            if (target[p] && typeof target[p] === 'object') {
                source[p] = mergeRecursive(source[p] || {}, target[p]);
            } else {
                source[p] = target[p];
            }
        } catch (e) {
            source[p] = target[p];
        }
    }
    return source;
}

/**
 * 构造树型结构数据
 * @param data 数据源
 * @param id id字段 默认 'id'
 * @param parentId 父节点字段 默认 'parentId'
 * @param children 孩子节点字段 默认 'children'
 */
export function handleTree(data: any[], id?: string, parentId?: string, children?: string): any[] {
    const config = {
        id: id || 'id',
        parentId: parentId || 'parentId',
        childrenList: children || 'children'
    };

    const childrenListMap: { [key: string]: any[] } = {};
    const nodeIds: { [key: string]: any } = {};
    const tree: any[] = [];

    for (const d of data) {
        const parentId = d[config.parentId];
        if (childrenListMap[parentId] == null) {
            childrenListMap[parentId] = [];
        }
        nodeIds[d[config.id]] = d;
        childrenListMap[parentId].push(d);
    }

    for (const d of data) {
        const parentId = d[config.parentId];
        if (nodeIds[parentId] == null) {
            tree.push(d);
        }
    }

    for (const t of tree) {
        adaptToChildrenList(t);
    }

    function adaptToChildrenList(o: any) {
        if (childrenListMap[o[config.id]] !== null) {
            o[config.childrenList] = childrenListMap[o[config.id]];
        }
        if (o[config.childrenList]) {
            for (const c of o[config.childrenList]) {
                adaptToChildrenList(c);
            }
        }
    }

    return tree;
}

/**
 * 参数处理
 * @param params 参数
 */
export function tansParams(params: any): string {
    let result = '';
    for (const propName of Object.keys(params)) {
        const value = params[propName];
        let part = encodeURIComponent(propName) + '=';
        if (value !== null && value !== '' && typeof value !== 'undefined') {
            if (typeof value === 'object') {
                for (const key of Object.keys(value)) {
                    if (value[key] !== null && value[key] !== '' && typeof value[key] !== 'undefined') {
                        let param = propName + '[' + key + ']';
                        let subPart = encodeURIComponent(param) + '=';
                        result += subPart + encodeURIComponent(value[key]) + '&';
                    }
                }
            } else {
                result += part + encodeURIComponent(value) + '&';
            }
        }
    }
    return result;
}

// 返回项目路径
export function getNormalPath(p: string): string {
    if (p.length === 0 || !p || p === 'undefined') {
        return p;
    }
    let res = p.replace('//', '/');
    if (res[res.length - 1] === '/') {
        return res.slice(0, res.length - 1);
    }
    return res;
}

// 验证是否为blob格式
export function blobValidate(data: any): boolean {
    return data.type !== 'application/json';
}

/**
 * 判断path是否为外链
 * @param {string} path
 * @returns {Boolean}
 */
export function isExternal(path:string):boolean {
    return /^(https?:|mailto:|tel:)/.test(path)
}
/**
 * 判断url是否是http或https
 * @param {string} path
 * @returns {Boolean}
 */
export function isHttp(url:string):boolean {
    return url.indexOf('http://') !== -1 || url.indexOf('https://') !== -1
}



/**
 * 添加日期范围
 *
 * @param params
 * @param dateRange
 * @param propName
 * @returns
 */
// prettier-ignore
export const addDateRange = (params: any, dateRange: any[], propName: string) => {
    let search = params;
    search.params = typeof (search.params) === 'object' && search.params !== null && !Array.isArray(search.params) ? search.params : {};
    dateRange = Array.isArray(dateRange) ? dateRange : [];
    if (dateRange) {
        if (typeof propName !== "undefined") {
            const firstCode = propName.substring(0, 1);
            if (!isUpCase(firstCode)) {
                propName = firstCode.toUpperCase() + propName.substring(1);
            } else {
                propName = firstCode + propName.substring(1);
            }
            search.params["begin" + propName] = dateRange[0];
            search.params["end" + propName] = dateRange[1];
        } else {
            search.params["beginTime"] = dateRange[0];
            search.params["endTime"] = dateRange[1];
        }
    }
    return search;
};
/**
 * 转换字符串，undefined,null等转化为""
 *
 * @param str 字符串
 * @returns
 */
export function praseStrEmpty(str: string) {
    if (!str || str == "undefined" || str == "null") {
        return "";
    }
    return str;
}
/**
 * 表单重置
 *
 * @param {string} formRef
 */
export const resetForm = (formRef: any) => {
    formRef.value?.resetFields();
};

